<template>
  <view class="market-container">
    <!-- 顶部标题栏（仅在APP和H5显示） -->
    <!-- #ifdef APP-PLUS || H5 -->
    <view class="header-wrapper">
      <view class="status-bar"></view>
      <view class="header">
        <uni-icons type="left" size="24" color="#333" @click="goBack"></uni-icons>
        <text class="header-title">选择市场</text>
        <view style="width: 24px;"></view>
      </view>
    </view>
    <!-- #endif -->

    <!-- 当前市场 -->
    <view class="current-section" v-if="currentMarket">
      <view class="section-title">当前市场</view>
      <view class="current-market-card">
        <view class="market-info">
          <text class="market-name">{{ currentMarket.deptName }}</text>
          <text class="market-address">{{ currentMarket.address || '暂无地址信息' }}</text>
        </view>
        <view class="selected-badge">
          <uni-icons type="checkmarkempty" size="16" color="#52c41a"></uni-icons>
          <text class="selected-text">当前</text>
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-box">
      <uni-icons type="search" size="20" color="#999"></uni-icons>
      <input 
        v-model="searchKeyword" 
        placeholder="搜索市场名称" 
        placeholder-style="color:#999"
        @input="handleSearch"
      />
      <uni-icons 
        v-if="searchKeyword" 
        type="clear" 
        size="20" 
        color="#999" 
        @click="clearSearch"
      ></uni-icons>
    </view>

    <!-- 市场列表 -->
    <view class="market-list">
      <view class="list-title">可选市场</view>
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      <view v-else-if="filteredMarkets.length === 0" class="empty">
        <uni-icons type="location" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无可选市场</text>
      </view>
      <view v-else>
        <view 
          v-for="market in filteredMarkets" 
          :key="market.deptId"
          class="market-item"
          :class="{ 
            'active': market.deptId === currentMarketId,
            'selected': selectedMarket && market.deptId === selectedMarket.deptId 
          }"
          @click="selectMarket(market)"
        >
          <view class="market-info">
            <text class="market-name">{{ market.deptName }}</text>
            <text class="market-address">{{ market.address || '暂无地址信息' }}</text>
            <view class="market-tags">
              <text class="tag" v-if="market.contactPerson">负责人: {{ market.contactPerson }}</text>
              <text class="tag" v-if="market.contactPhone">电话: {{ market.contactPhone }}</text>
            </view>
          </view>
          <uni-icons 
            v-if="market.deptId === currentMarketId" 
            type="checkmarkempty" 
            size="24" 
            color="#52c41a"
          ></uni-icons>
          <uni-icons 
            v-else-if="selectedMarket && market.deptId === selectedMarket.deptId" 
            type="circle" 
            size="24" 
            color="#1890ff"
          ></uni-icons>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-btn" v-if="selectedMarket && selectedMarket.deptId !== currentMarketId">
      <button class="confirm-btn" @click="confirmSwitch">确认切换</button>
    </view>
  </view>
</template>

<script>
import { getMarketList, getCurrentUserMarket, switchUserMarket } from '@/api/market'

export default {
  data() {
    return {
      loading: false,
      searchKeyword: '',
      marketList: [],
      currentMarket: null,
      currentMarketId: null,
      selectedMarket: null
    }
  },
  computed: {
    filteredMarkets() {
      if (!this.searchKeyword) {
        return this.marketList
      }
      return this.marketList.filter(market => 
        market.deptName.includes(this.searchKeyword)
      )
    }
  },
  onLoad() {
    this.loadCurrentMarket()
    this.loadMarketList()
  },
  methods: {
    // 返回
    goBack() {
      uni.navigateBack({
        delta: 1
      })
    },
    
    // 清空搜索
    clearSearch() {
      this.searchKeyword = ''
    },
    
    // 搜索处理
    handleSearch() {
      // 搜索逻辑已在computed中处理
    },
    
    // 加载当前市场信息
    async loadCurrentMarket() {
      try {
        // 从服务器获取用户当前的市场
        const res = await getCurrentUserMarket()
        if (res.code === 200 && res.data) {
          this.currentMarket = {
            deptId: res.data.deptId,
            deptName: res.data.deptName,
            address: res.data.address || '',
            contactPerson: res.data.contactPerson || '',
            contactPhone: res.data.contactPhone || ''
          }
          this.currentMarketId = res.data.deptId
        } else {
          // 如果用户还没有设置市场，获取市场列表并设置第一个为默认
          const listRes = await getMarketList()
          if (listRes.code === 200 && listRes.data && listRes.data.length > 0) {
            const defaultMarket = listRes.data[0]
            // 自动设置第一个市场为用户的默认市场
            await switchUserMarket(defaultMarket.deptId)
            this.currentMarket = {
              deptId: defaultMarket.deptId,
              deptName: defaultMarket.deptName,
              address: defaultMarket.address || '',
              contactPerson: defaultMarket.contactPerson || '',
              contactPhone: defaultMarket.contactPhone || ''
            }
            this.currentMarketId = defaultMarket.deptId
          }
        }
      } catch (error) {
        console.error('加载当前市场失败:', error)
      }
    },
    
    // 加载市场列表
    async loadMarketList() {
      this.loading = true
      try {
        // 调用后端接口获取真实市场数据
        const res = await getMarketList()
        if (res.code === 200 && res.data) {
          // 过滤掉当前市场，只显示可切换的市场
          this.marketList = res.data.filter(m => m.deptId !== this.currentMarketId)
        } else {
          this.marketList = []
        }
      } catch (error) {
        console.error('加载市场列表失败:', error)
        uni.showToast({
          title: '加载市场列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 选择市场
    selectMarket(market) {
      this.selectedMarket = market
    },
    
    // 确认切换
    async confirmSwitch() {
      if (!this.selectedMarket) {
        return
      }
      
      uni.showModal({
        title: '确认切换',
        content: `确定要切换到"${this.selectedMarket.deptName}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '切换中...' })
            try {
              // 调用后端接口切换市场
              const result = await switchUserMarket(this.selectedMarket.deptId)
              
              if (result.code === 200) {
                uni.hideLoading()
                uni.showToast({
                  title: '切换成功',
                  icon: 'success'
                })
                
                // 返回上一页
                setTimeout(() => {
                  uni.navigateBack()
                }, 1500)
              } else {
                uni.hideLoading()
                uni.showToast({
                  title: result.msg || '切换失败',
                  icon: 'none'
                })
              }
            } catch (error) {
              uni.hideLoading()
              console.error('切换市场失败:', error)
              uni.showToast({
                title: '切换失败，请重试',
                icon: 'none'
              })
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.market-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部标题栏 */
.header-wrapper {
  background-color: #fff;
  border-bottom: 1rpx solid #e8e8e8;
}

.status-bar {
  /* #ifdef APP-PLUS */
  height: var(--status-bar-height);
  /* #endif */
  /* #ifdef MP-WEIXIN */
  height: 44px; /* 微信小程序状态栏固定高度 */
  /* #endif */
  /* #ifdef H5 */
  height: 0;
  /* #endif */
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.header-title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

/* 当前市场 */
.current-section {
  margin: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.current-market-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.selected-badge {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  background: #f0f9ff;
  border-radius: 20rpx;
}

.selected-text {
  font-size: 24rpx;
  color: #52c41a;
  margin-left: 5rpx;
}

/* 搜索框 */
.search-box {
  display: flex;
  align-items: center;
  margin: 20rpx;
  padding: 20rpx 30rpx;
  background: #fff;
  border-radius: 12rpx;
}

.search-box input {
  flex: 1;
  margin: 0 20rpx;
  font-size: 28rpx;
}

/* 市场列表 */
.market-list {
  margin: 20rpx;
}

.list-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.market-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  transition: all 0.3s;
}

.market-item:active {
  background: #f0f9ff;
}

.market-item.active {
  background: #f0f9ff;
  border: 2rpx solid #52c41a;
}

.market-item.selected {
  background: #e6f7ff;
  border: 2rpx solid #1890ff;
}

.market-info {
  flex: 1;
}

.market-name {
  display: block;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
}

.market-address {
  display: block;
  font-size: 26rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.market-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 10rpx;
}

.tag {
  padding: 4rpx 12rpx;
  background: #f0f2f5;
  border-radius: 4rpx;
  font-size: 24rpx;
  color: #666;
}

/* 空状态 */
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  background: #fff;
  border-radius: 12rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  background: #fff;
  border-radius: 12rpx;
}

/* 底部按钮 */
.bottom-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 44rpx;
  border: none;
}

.confirm-btn:active {
  opacity: 0.9;
}
</style>